"""
线程间通信-共享变量（需要加锁，不推荐使用）
"""

import time
import threading

# 不能直接导入变量，不然其他线程修改它时，该线程看不到
from chapter11 import c03_thread_com_var


class GetDetailHtml(threading.Thread):
    """
    通过继承Thread类来实现多线程（复杂逻辑推荐使用）
    """

    def __init__(self, name):
        super().__init__(name=name)

    def run(self):
        detail_url_list = c03_thread_com_var.detail_url_list
        while True:
            if len(c03_thread_com_var.detail_url_list):
                url = detail_url_list.pop()

                print("get detail html started")
                time.sleep(2)
                print("get detail html end")


class GetDetailUrl(threading.Thread):
    def __init__(self, name):
        super().__init__(name=name)

    def run(self):
        while True:
            print("get detail url started")
            time.sleep(2)

            for i in range(20):
                c03_thread_com_var.detail_url_list.append("http://projectsedu.com/{id}".format(id=i))

            print("get detail url end")


def use_thread_extend():
    t1 = GetDetailHtml(name="GetDetailHtml")

    t_list = []
    for i in range(10):
        t2 = GetDetailUrl(name="GetDetailUrl")
        t_list.append(t2)

    t1.start()
    for t in t_list:
        t.start()

    # 线程阻塞
    t1.join()
    for t in t_list:
        t.join()


if __name__ == '__main__':
    use_thread_extend()
